<?php

namespace app\admin\controller\routine;

use app\common\controller\Backend;
use app\common\model\Attachment as AttachmentModel;
use Exception;
use think\db\exception\PDOException;
use think\facade\Event;

class Attachment extends Backend
{
    protected $model = null;

    /**
     * 快速搜索字段
     * @var string[]
     */
    protected $quickSearchField = 'name';

    protected $withJoinTable = ['admin'];

    /**
     * 查看请求返回的主表字段控制
     */
    protected $indexField = ['id', 'topic', 'size', 'admin_id', 'mime_type', 'url', 'quote',
                             'name', 'storage', 'last_upload_time'];

    protected $defaultSortField = 'last_upload_time,desc';

    public function initialize()
    {
        parent::initialize();
        $this->model = new AttachmentModel();
    }

    /**
     * 删除
     * @param array $ids
     */
    public function del(array $ids = [])
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
        }

        $pk    = $this->model->getPk();
        $data  = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        try {
            foreach ($data as $v) {
                Event::trigger('AttachmentDel', $v);
                $filePath = path_transform(public_path() . ltrim($v->url, '/'));
                if (file_exists($filePath) && $v->storage == 'local') {
                    unlink($filePath);
                    del_empty_dir(dirname($filePath));
                }
                $count += $v->delete();
            }
        } catch (PDOException|Exception $e) {
            $this->error("已删除{$count}条记录和文件" . $e->getMessage());
        }
        if ($count) {
            $this->success("已删除{$count}条记录和文件");
        } else {
            $this->error('删除失败！');
        }
    }
}
